//
//  PTSTabBarButton.m
//  PTS80
//
//  Created by 黄杰 on 15/11/3.
//  Copyright © 2015年 黄杰. All rights reserved.
//
#define kImageW 35
#define kImageH 30
#define kMargin 5

#import "PTSTabBarButton.h"
#import "PTSBadgeButton.h"

@interface PTSTabBarButton ()
@property (nonatomic, weak) PTSBadgeButton *badge;
@end

@implementation PTSTabBarButton

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
//        self.imageView.backgroundColor = [UIColor blueColor];
        self.imageView.contentMode = UIViewContentModeScaleAspectFit;
        PTSBadgeButton *badge = [PTSBadgeButton buttonWithType:UIButtonTypeCustom];
        [self addSubview:badge];
        self.badge = badge;
    }
    return self;
}

- (void)setHighlighted:(BOOL)highlighted
{
    
}

- (void)setSelected:(BOOL)selected
{
    [super setSelected:selected];
    if (selected) {
        self.backgroundColor = self.itemColor;
    } else {
        self.backgroundColor = [UIColor clearColor];
    }
}

- (CGRect)imageRectForContentRect:(CGRect)contentRect
{
    CGFloat imageW = kImageW;
    CGFloat imageH = kImageH;
    CGFloat imageX = (contentRect.size.width - imageW) * 0.5;
    CGFloat imageY = 0;
    return CGRectMake(imageX, imageY, imageW, imageH);
//    CGFloat imageW = contentRect.size.width;
//    CGFloat imageH = contentRect.size.height;
//    CGFloat imageX = 0;
//    CGFloat imageY = 0;
//    return CGRectMake(imageX, imageY, imageW, imageH);
}

- (CGRect)titleRectForContentRect:(CGRect)contentRect
{
    CGFloat titleX = 0;
    CGFloat titleW = contentRect.size.width;
    CGFloat titleH = 20;
    CGFloat titleY = kImageH - 3;
    return CGRectMake(titleX, titleY, titleW, titleH);
}

- (void)setItem:(UITabBarItem *)item
{
    _item = item;
    
    // kvo监听
    [item addObserver:self forKeyPath:@"badgeValue" options:0 context:nil];
}

- (void)dealloc
{
    [self.item removeObserver:self forKeyPath:@"badgeValue"];
}

/**
 *  监听到某个对象属性改变
 *
 *  @param keyPath 属性名
 *  @param object  哪个对象的属性被改了
 *  @param change  属性发生的一些改变
 */
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    //        NSLog(@"---%@的%@属性被修改了", object, keyPath);
    
    //  设置提醒数字
    self.badge.badgeValue = self.item.badgeValue;
    
    // 设置提醒数字位置
    CGFloat badgeY = 5;
    CGFloat badgeW = 18;
    CGFloat badgeH = 18;
    CGFloat badgeX = self.frame.size.width - badgeW - 5;
    
    self.badge.frame = CGRectMake(badgeX, badgeY, badgeW, badgeH);
}

@end
